package com.xqkad.myplayer.utils;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;
import android.support.v4.content.ContextCompat;

import com.xqkad.myplayer.info.MusicInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class AudioTools {

    public static List<MusicInfo> getNetMusicInfoList(String title){
        List<MusicInfo> list;
        String url1 = "https://mp.weixin.qq.com/mp/audio?t=pages/audio_detail&__biz=MjM5MDQ4MzU5NQ==&mid=2658992927&idx=1&sn=e3e180ba2fae9b0c78d64d7c693b24a0&voice_id=MjM5MDQ4MzU5NV8yNjU4OTkyOTI2&_wxindex_=0&from=singlemessage&scene=1&subscene=10000&clicktime=1584445298&enterid=1584445298&pass_ticket=EZtJILKqYjKAq4cUhvoSn0Pem3th3%2B6EOaqGiQhkPi0%3D";
        String url2 = "https://mp.weixin.qq.com/mp/audio?t=pages/audio_detail&__biz=MzIxNTcyOTM2MA==&mid=2247493293&idx=1&sn=fb65068f2afe2c100d0d181b9fb14b6c&voice_id=MzIxNTcyOTM2MF8yMjQ3NDkzMjky&_wxindex_=0&from=singlemessage&scene=1&subscene=10000&clicktime=1584450769&enterid=1584450769&pass_ticket=EZtJILKqYjKAq4cUhvoSn0Pem3th3%2B6EOaqGiQhkPi0%3D";
        if(title.equals("科技美学")){
            list = getNetMusicInfoList_impl(url1);
        }else{
            list = getNetMusicInfoList_impl(url2);
        }
        return list;
    }

    private static List<MusicInfo> getNetMusicInfoList_impl(String url){
        final List<MusicInfo> list = new ArrayList<MusicInfo>();
        //Log.d("mytag", "thead: "+Thread.currentThread().getName());Thread-4
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            String str = response.body().string();
            //Log.d("mytag","abc "+abc.length());
            if(str != null && str.length()>  0)
                list.addAll(getNetList(str));
        } catch (Exception e) {
            return null;
        }
        return list;
    }
    private static List<MusicInfo> getNetList(String str){
        ArrayList<MusicInfo> list = new ArrayList<MusicInfo>();
        String regex = "history : \\[";
        int start = getStart(regex,str);
        if(start == -1)
            return list;
        regex = "title : \"";
        String[] titles = regexStr(regex,str, start);
        regex = "voiceid : \"";
        String[] voiceids = regexStr(regex,str,start);
        if(titles != null && voiceids != null && titles.length == voiceids.length){
            for (int i = 0; i < titles.length; i++) {
                MusicInfo info = new MusicInfo();
                info.id = voiceids[i];
                info.isNet = true;
                info.title = titles[i];
                info.data = voiceids[i];
                list.add(info);
            }
        }
        return list;
    }
    private static int getStart(String regex, String input){
        int r = -1;
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(input);
        int w=0;
        while(m.find()){
            w++;
            r = m.start();
        }
        if(w != 1)
            r = -1;
        return r;
    }
    private static String[] regexStr(String regexA, String input, int start){
        String[] r = null;
        String regex = regexA+"(.*?)"+"\"";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(input);
        ArrayList<String> list = new ArrayList<String>();
        while(m.find()){
            if(m.start() > start)
                list.add(m.group(1));
        }
        //Log.d("mytag", "whiled listsize = "+list.size());
        if(list.size() > 0){
            r = new String[list.size()];
            for(int i=0;i<list.size();i++){
                r[i] = list.get(i);
            }
        }
        //Log.d("mytag",r);
        return r;
    }

    public static List<MusicInfo> getMusicInfoList(Context context){
        if(!checkPermission((Activity) context))
            return null;
        ContentResolver cr = context.getContentResolver();
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String[] proj_music = new String[]{
                Media._ID, Media.TITLE,
                Media.DATA, Media.ALBUM_ID,
                Media.ALBUM, Media.ARTIST,
                Media.ARTIST_ID, Media.DURATION, Media.SIZE};
        String select = "1=1 and title != '' and _size > 1048576 and duration > 60000";
        String sortOrder = MediaStore.Audio.Media.DEFAULT_SORT_ORDER;
        Cursor cursor = cr.query(uri, proj_music, select, null, sortOrder);

        return getMusicInfoList(cursor);
    }

    public static String getFolderPath(MusicInfo musicInfo){
        return musicInfo.data.substring(0, musicInfo.data.lastIndexOf(File.separator));
    }

    private static List<MusicInfo> getMusicInfoList(Cursor cursor){
        if(cursor == null)
            return null;
        ArrayList<MusicInfo> list = new ArrayList<MusicInfo>();
        while(cursor.moveToNext()){
            MusicInfo info = new MusicInfo();
            info.id = cursor.getString(cursor.getColumnIndex(
                    Media._ID));
            info.title = cursor.getString(cursor.getColumnIndex(
                    Media.TITLE));
            info.data = cursor.getString(cursor.getColumnIndex(
                    Media.DATA));
            //music.folder = filePath.substring(0, filePath.lastIndexOf(File.separator));
            info.album_id = cursor.getInt(cursor.getColumnIndex(
                    Media.ALBUM_ID));
            info.album = cursor.getString(cursor.getColumnIndex(
                    Media.ALBUM));
            info.artist = cursor.getString(cursor.getColumnIndex(
                    Media.ARTIST));
            info.artist_id = cursor.getLong(cursor.getColumnIndex(
                    Media.ARTIST_ID));
            info.duration = cursor.getInt(cursor.getColumnIndex(
                    Media.DURATION));
            info.size = cursor.getInt(cursor.getColumnIndex(
                    Media.SIZE));
            list.add(info);
        }
        cursor.close();

        return list;
    }

    public static boolean checkPermission(Activity activity) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            int p = ContextCompat.checkSelfPermission(activity
                    ,Manifest.permission.READ_EXTERNAL_STORAGE);
            if(p == PackageManager.PERMISSION_GRANTED){
                return true;
            }
        }
        return false;
    }

    public static String makeTimeString(int millis) {
        if(millis >= 60 * 60 * 1000)
            return "60:00";
        StringBuffer sb = new StringBuffer();
        int m = millis / (60 * 1000);
        sb.append(m < 10 ? "0" + m : m);
        sb.append(":");
        int s = (millis % (60 * 1000)) / 1000;
        sb.append(s < 10 ? "0" + s : s);
        return sb.toString();
    }

}
